<?php
/**
 * 获取淘宝API授权信息
 * */
class LoginController extends Controller {
	
	/*
	 *淘宝登录名
	 */ 
	private $TAOBAO_USER = 'cljdragon';
	
	/**
	 * 获取授权跳转
	 * sdfasdfsadfsd
	 */
	public function actionIndex() {
		$url = 'http://container.api.taobao.com/container?appkey='.Yii::app()->top->appkey.'&encode=utf-8';	
		$this->redirect($url);	
	}
	 
	 /**
	 * 淘宝网TopApi登录
	 */
	public function actionTaobao($top_session = null,$top_sign = null,$top_parameters = null) {			

		$req = new UserGetRequest;
		$req->setFields("user_id,uid,nick,sex,created,last_visit,type,alipay_bind,avatar,email");
		$resp = Yii::app()->top->execute($req, $top_session);			
		if(!$resp || $resp->user->nick!=$this->TAOBAO_USER){
			print_r($resp);
			Yii::app()->end();
		}	
		
		$conts = "'tokey' => array(
		'top_session'=>'{$top_session}',
		'refresh_tokey'=>'".$this->getParameters($top_parameters,'refresh_token')."',
		),\n";
		
		foreach ($resp->user as $key => $list) {
			$s .= "'{$key}'=>'{$list}',\n";
		}
		$conts .= "'user' => array(\n{$s}\n),\n";
		
		$req = new ShopGetRequest;
		$req->setFields("sid,user_id,cid,title,desc,bulletin,pic_path,created,modified,remain_count,all_count,used_count");
		$req->setNick($this->TAOBAO_USER);
		$resp = Yii::app()->top->execute($req);
		if($resp->shop){
			foreach ($resp->shop as $key => $list) {
				$s2 .= "'{$key}'=>'{$list}',\n";
			}
			$conts .= "'shop' => array(\n$s2\n),\n";
		}
		$handle = fopen(dirname(__FILE__).'/../messages/zh_cn/tokey.php', 'w'); 		
		if(fwrite($handle, "<?php\nreturn array(\n{$conts}\n);")){
			echo Yii::t("{$this->module->id}Module.main","return api ok");	
		}else{
			echo Yii::t("{$this->module->id}Module.main","return api wreiterror");
		}
		fclose($handle);
	}

	public function actionRefresh() {
		$ttokey = Yii::t("{$this->module->id}Module.tokey","tokey");
		$parameter = "appkey=".Yii::app()->top->appkey."&refresh_token={$ttokey[refresh_tokey]}&sessionkey={$ttokey[top_session]}";
		$parame = str_replace('=','',$parameter);
		$parame = str_replace('&','',$parameter);

		$sign = strtoupper(md5($parame.Yii::app()->top->secretKey));
		$url = "http://container.open.taobao.com/container/refresh?{$parameter}&sign=$sign";
		echo $url;
	}

	private function getParameters($top_parameters,$key){
		$_refresh_token = explode('&',base64_decode($top_parameters));
		foreach($_refresh_token as $list){
			$val = explode('=',$list);
			if($val[0] == $key){
				return $val[1];
			}
		}
	}

	/*登出*/
	public function actionLogout() {
		$topouturl = "https://oauth.taobao.com/logoff?client_id=".Yii::app()->top->appkey."&redirect_uri=http://".$_SERVER['HTTP_HOST'].$this->createUrl('login/index');	
		Yii::app()->user->logout();
		$this->redirect(array("login/index"));
	}
	
}















